package com.joysuch.wwyt.streampusher;

import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qingzhou
 * 2018/5/22
 */
public class ShellScriptExecutor {
    private static final Logger logger = LoggerFactory.getLogger(ShellScriptExecutor.class);

    public static List<String> executeShell(String shellScript, String dir) {
        List<String> processList = new ArrayList<>();
        BufferedReader bufferedReader = null;
        try {
            logger.info("======执行Shell:" + shellScript + "=======");
            Process pid = null;
            //Linux下
            String[] cmd = {"/bin/sh", "-c", shellScript};
//            windows下
//            String[] cmd = {"cmd", "/c", shellScript};

            if (!Strings.isNullOrEmpty(dir))
                pid = Runtime.getRuntime().exec(cmd, null, new File(dir));
            else {
                pid = Runtime.getRuntime().exec(cmd);
            }
            if (pid != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
                pid.waitFor();
            }
            String line = null;

            while ((bufferedReader != null) && ((line = bufferedReader.readLine()) != null)) {
                logger.info(line);
                processList.add(line);
            }
        } catch (Exception ioe) {
            logger.error("执行Shell命令时发生异常：\r\n" + ioe.getMessage());
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        for (String line : processList) {
            logger.info(line);
        }
        return processList;
    }
}
